import subprocess
from nicegui import ui


def evaluate_code(student_code, correct_code):
    try:
        # 将学生代码写入文件
        with open("student_code.py", "w") as file:
            file.write(student_code)

        # 尝试运行学生代码
        result = subprocess.run(["python", "student_code.py"], capture_output=True, text=True)

        # 检查是否有编译错误
        if result.returncode != 0:
            return False, f"编译错误：\n{result.stderr}"

        student_output = result.stdout.strip()  # 学生代码的输出

        # 执行正确的代码
        result = subprocess.run(["python", "-c", correct_code], capture_output=True, text=True)
        correct_output = result.stdout.strip()  # 正确代码的输出

        # 比较学生输出和正确输出
        if student_output == correct_output:
            return True, "答案正确！"
        else:
            return False, "答案不正确。"
    except Exception as e:
        return False, f"运行时错误：{e}"

    # 示例使用方法
intput = ""

def change(e):
    global intput
    intput=e.value
    label.set_text(intput)
def ondick():
    if_true, text = evaluate_code(intput, "print(2)")
    print(intput)
    ui.notify(text)
    print(text)
    print("111111111111")


options=['print','if','True','False','else','import','def',]
ui.label('1+1等于??')
ui.textarea('输入代码',value=intput,on_change=lambda e:change(e)).on('keydown.enter')
with ui.column():
    for i in range(5):
        ui.input(f"第{i}行")
label = ui.label("")
ui.button('提交', on_click=ondick)

ui.run(uvicorn_reload_excludes="student_code.py")
